package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.entity.Coupon;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.entity.CouponProductRegionRelation;
import com.chen.mapper.CouponMapper;
import com.chen.mapper.CouponProductRegionRelationMapper;
import com.chen.mapper.CouponProductRelationMapper;
import com.chen.service.CouponService;
import com.chen.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 优惠券表 服务实现类
 * </p>
 *
 * @author cws
 * @since 2024-11-22
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {


    @Resource
    private CouponProductRegionRelationMapper couponProductRegionRelationMapper;

    @Resource
    private CouponProductRelationMapper couponProductRelationMapper;

    /**
     * 根据商品获取指定优惠卷及不指定优惠卷
     *
     * @param productId
     * @return
     */
    @Override
    public Result couponList(Long productId,Long regionId) {
//        获取当前时间
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<Coupon> wrapper = new LambdaQueryWrapper<>();
//        当前时间大于了开始时间
        wrapper.gt(Coupon::getEnableTime, now);
//        当前时间小于了结束时间
        wrapper.lt(Coupon::getEndTime, now);
//        先查全场可用全
        wrapper.eq(Coupon::getUseType, 0);
        List<Coupon> coupons = baseMapper.selectList(wrapper);
        //再查指定商品可用优惠卷
        List<Coupon> couponProductRelation = couponProductRelationMapper.selectByProductId(productId);
        //查询对应地区
        List<Coupon> couponProductRegionRelation = couponProductRegionRelationMapper.selectByRegionId(regionId);
//        合并去重
        if (couponProductRelation != null&&couponProductRelation.size()>0){
            coupons.addAll(couponProductRelation);
        }
        if (couponProductRegionRelation != null&&couponProductRegionRelation.size()>0){
            coupons.addAll(couponProductRegionRelation);
        }
        return Result.success(coupons);
    }
}
